package com.minelx.sqlstructures.statements;

import com.minelx.sqlstructures.core.values.FieldValues;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.joining;

public class CreateTableStatement {
	private final String tableName;

	private final List<FieldValues> fields;

	private boolean ifNotExists;

	public CreateTableStatement(String tableName) {
		this.tableName = tableName;
		fields = new ArrayList<>();
	}

	public CreateTableStatement append(FieldValues appended) {
		fields.add(appended);
		return this;
	}

	public CreateTableStatement appendAll(List<FieldValues> appended) {
		fields.addAll(appended);
		return this;
	}

	public CreateTableStatement primary(String name, String type) {
		return append(new FieldValues(fields.size(), name, type, "", true));
	}

	public CreateTableStatement field(String name, String type) {
		return append(new FieldValues(fields.size(), name, type, "", false));
	}

	public CreateTableStatement fields(Map<String, String> fields) {
		fields.forEach(this::field);
		return this;
	}

	public CreateTableStatement ifNotExists() {
		ifNotExists = true;
		return this;
	}

	public String toSql() {
		StringBuilder result = new StringBuilder();
		result.append("CREATE TABLE ");
		if (ifNotExists) {
			result.append("IF NOT EXISTS ");
		}
		result.append(tableName);
		result.append(" (");

		result.append(fields.stream()
				.sorted(comparingInt(FieldValues::getIndex))
				.map(FieldValues::representSql)
				.collect(joining(", ")));
//		result.append(String.join(", ", fields));
		result.append(");");
		return result.toString();
	}
}
